<?php

/**
 * Holds class Config
 *
 * @author Mark
 *
 * @package Library
 */

/**
 * Configuration management
 *
 * @author Mark
 */
class Config {

	/**
	 * Configuration vars
	 * @var array $_item
	 */
	protected $_item = array();

	/**
	 * Constructor
	 *
	 * @return void
	 */
	public function __construct() {
		//
	}

	/**
	 * Exports configuration
	 *
	 * @return array
	 */
	public function export($depth = "") {
		$result = array();
		foreach($this->_item as $key => $value) {
			$path = "{$depth}_{$key}";
			if($value instanceof self) {
				$result[$key] = $value->export($path);
			}
			else {
				$result[$key] = (null === $value) ? ltrim($path,"_") : $value;
			}
		}
		return $result;
	}

	public function __get($var){
		return $this->get($var);
	}
	
	/**
	 * Returns configuration item
	 *
	 * @param string $key
	 * @throws Exception
	 * @return mixed
	 */
	public function get($key) {
		if(!isset($this->_item[$key])) {
			throw new Exception('Configuration item ' . $key . ' does not exist');
		}
		return $this->_item[$key];
	}

	/**
	 * Imports configuration file
	 *
	 * @param string $file
	 * @throws Exception
	 * @return Config (fluent interface)
	 */
	public function import($file) {
		if(!file_exists($file)) {
			throw new Exception('Configuration file ' . $file . ' does not exist');
		}

		// Import and save
		$data = include $file;
		if(!(isset($data) && is_array($data))) {
			throw new Exception('Configuration file ' . $file . ' has an incorrect format');
		}

		// Import
		foreach($data as $key => $value) {
			$this->set($key, $value);
		}
		
		return $this;
	}

	/**
	 * Removes configuration section
	 *
	 * @param string $key
	 * @throws Exception
	 * @return Config (fluent interface)
	 */
	public function remove($key) {
		if(!isset($this->_item[$key])) {
			throw new Exception('Configuration section ' . $key . ' does not exist');
		}
		unset($this->_item[$key]);
		return $this;
	}

	/**
	 * Sets configuration item
	 *
	 * @param string $key
	 * @param mixed $value
	 * @return Config (fluent interface)
	 */
	public function set($key, $value) {
		if(is_array($value)) {
			$this->_item[$key] = new Config();
			foreach($value as $k => $v) {//import
				$this->_item[$key]->set($k, $v);
			}
		}
		else {
			$this->_item[$key] = ($value === null) ? null : $value;
		}

		return $this;
	}

}
